<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
        <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
        <el-steps :space="200" :active="activeNum" align-center finish-status="success">
            <el-step title="基本信息"></el-step>
            <el-step title="商品参数"></el-step>
            <el-step title="商品属性"></el-step>
            <el-step title="商品图片"></el-step>
            <el-step title="商品内容"></el-step>
            <el-step title="完成"></el-step>
        </el-steps>
        <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="100px" class="demo-ruleForm" label-position="top">
        <!--tabs-->
        <el-tabs tab-position="left"  v-model="activeName"  :before-leave="beforeLeave" @tab-click="tabClicked">
            <el-tab-pane label="基本信息" name="0">
                <el-form-item label="商品名称" prop="goods_name">
                    <el-input v-model="ruleForm.goods_name"></el-input>
                </el-form-item>
                <el-form-item label="商品价格" prop="goods_price">
                    <el-input v-model="ruleForm.goods_price" type="number"></el-input>
                </el-form-item>
                <el-form-item label="商品重量" prop="goods_weight">
                    <el-input v-model="ruleForm.goods_weight" type="number"></el-input>
                </el-form-item>
                <el-form-item label="商品数量" prop="goods_number">
                    <el-input v-model="ruleForm.goods_number" type="number"></el-input>
                </el-form-item>
                <el-form-item label="商品分类" required>
                    <el-cascader clearable
                    v-model="ruleForm.goods_cat"
                    :options="type3CateList"
                    :props="cascaderProps"
                    @change="cascaderChange">
                </el-cascader>
                </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品动态参数" name="1">
                <el-form-item v-for="(item,index) in manyList" :key="index" :label="item.attr_name">
                    <el-checkbox-group v-model="item.attr_vals">
                        <el-checkbox border :label="sunitem" v-for="(sunitem,index2) in item.attr_vals" :key="index2"></el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品静态属性" name="2">
                <el-form-item v-for="item in onlyList" :key="item.attr_id" :label="item.attr_name">
                    <el-input v-model="item.attr_vals"></el-input>
                </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="商品图片" name="3">
                <el-upload
                action="http://127.0.0.1:8888/api/private/v1/upload"
                :headers="headerObj"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-success="handelSuccess"
                list-type="picture">
                <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
            </el-tab-pane>
            <el-tab-pane label="商品内容" name="4">
                <!-- bidirectional data binding（双向数据绑定） -->
                <quill-editor v-model="ruleForm.goods_introduce"
                ref="myQuillEditor">
                </quill-editor>
                <el-button size="large" type="primary" class="finalBtn" @click="addAll">添加商品</el-button>
            </el-tab-pane>
        </el-tabs>
        </el-form>
    </el-card>
    <el-dialog :visible.sync="imgDialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data() {
      var checkPrice = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('不能为0或空值'));
        }
      };
    return {
        activeNum:0,
        activeName:'0',
        ruleForm:{
            goods_name:'测试使用',
            goods_price:1,
            goods_weight:1,
            goods_number:1,
            goods_cat:[1,3,6],
            pics:[],
            goods_introduce:'',
            attrs:[]
        },
        rules:{
            goods_name:[
                { required: true, message: '请输入', trigger: 'blur' },
                {
                    min: 1,
                    max: 10,
                    message: '长度在1~10个字符之间',
                    trigger: 'blur'
                }
            ],
            goods_price:[
                { required: true, message: '请输入', trigger: 'blur' },
                { validator: checkPrice, trigger: 'blur' }
            ],
            goods_weight:[
                { required: true, message: '请输入', trigger: 'blur' },
                { validator: checkPrice, trigger: 'blur' }
            ],
            goods_number:[
                { required: true, message: '请输入', trigger: 'blur' },
                { validator: checkPrice, trigger: 'blur' }
            ]
        },
        type3CateList:[],
        selectedKey:[],
        cascaderProps:{
            value:'cat_id',
            label:'cat_name',
            children:'children'
        },
        manyList:[],
        onlyList:[],
        headerObj:{
            Authorization:window.sessionStorage.getItem("token")
        },
        imgDialogVisible:false,
        dialogImageUrl:''
    }
  },
  created(){
      this.getCurrentCateList()
  },
  methods: {
      async getCurrentCateList(){
          const {data:res} =await this.$http.get('categories',{params:{type:3}})
          if(res.meta.status != 200) return this.$message.error('获取数据失败')
          console.log(`${res.data}`)
          this.type3CateList = res.data;
      },
      cascaderChange(){
          console.log(this.ruleForm.goods_cat)
          if(this.ruleForm.goods_cat.length != 3) this.ruleForm.goods_cat = []
      },
      beforeLeave(an,oan){
          
          //第一个标签页面进行切换之前先进行验证，该页的数据是否完成填写
          if(oan == '0'){
              if(this.ruleForm.goods_cat.length != 3 || this.ruleForm.goods_name == '' || parseFloat(this.ruleForm.goods_price).toString()=='NaN' || parseFloat(this.ruleForm.goods_weight).toString()=='NaN' || parseInt(this.ruleForm.goods_number).toString()=='NaN'){
                  console.log(this.ruleForm)
                 // console.log(parseFloat(this.ruleForm.goods_price).toString())
                  this.$message.warning('请完成必填项的表单');
                  return false;
              }
              else
                  return true;
          }

      },
      tabClicked(){
          console.log(this.activeName)
          this.activeNum = parseInt(this.activeName)
          if(this.activeName == '1') //点击第二个面板。即将获取数据
          {
              this.getDTData()
          }
          else if(this.activeName == '2')
          {
              this.getJTData()
          }
      },
      async getDTData(){
          const {data:res} = await this.$http.get(`categories/${this.getCateId}/attributes`,{params:{sel:'many'}});
          if(res.meta.status != 200) return this.$message.error('动态参数获取失败了');
          res.data.forEach(item =>{
              item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : [];
          })
          this.manyList = res.data;
          console.log(this.manyList)
      },
      async getJTData(){
          const {data:res} = await this.$http.get(`categories/${this.getCateId}/attributes`,{params:{sel:'only'}});
          if(res.meta.status != 200) return this.$message.error('静态属性获取失败了');
        //   res.data.forEach(item =>{
        //       item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : [];
        //   })
          this.onlyList = res.data;
          console.log(this.onlyList)
      },
      handlePreview(file){
          console.log(file)
          this.dialogImageUrl = file.url;
          this.imgDialogVisible = true;
      },
      handleRemove(file){
         // console.log(file);
          const delPic = file.response.data.tmp_path;
          var i = this.ruleForm.pics.findIndex(item =>item.tmp_path === delPic)
          this.ruleForm.pics.splice(i,1)
          //console.log(this.ruleForm.pics)
      },
      handelSuccess(response){
          console.log(response)
          const picInfo = {
              pic:response.data.tmp_path
          }
          this.ruleForm.pics.push(picInfo);
          //console.log(this.ruleForm)
      },
      async addAll(){
          this.$refs.ruleFormRef.validate(async valid=>{
              if(!valid) return this.$message.error('表单验证不通过，请检查')
              //表单通过
              //先对数据进行处理,记得先将数据深拷贝一份，避免这边对ruleForm数据操作之后影响到了上面的表单的绑定
              const form = _.cloneDeep(this.ruleForm)
              form.goods_cat = form.goods_cat.join(',')
              this.manyList.forEach(item=>{
                  const manyInfo = {
                      attr_id:item.attr_id,
                      attr_vals:item.attr_vals.join(',')
                  }
                  form.attrs.push(manyInfo)
              })
              this.onlyList.forEach(item=>{
                  const onlyInfo = {
                      attr_id:item.attr_id,
                      attr_vals:item.attr_vals
                  }
                  form.attrs.push(onlyInfo)
              })
              console.log(form)
              const {data:res} = await this.$http.post('goods',form);
              if(res.meta.status != 201) return this.$message.error('数据添加失败了')
              this.$message.success('添加成功')
              this.$router.push('/goods')
          })
      }
  },
  components: {

  },
  computed:{
      //获取数组中最后的数字
      getCateId(){
          if(this.ruleForm.goods_cat.length == 3) return this.ruleForm.goods_cat[2];
          return null
      },
  }
}
</script>

<style lang='less' scoped>

.el-steps{
    margin: 15px 0;
}
.el-step__title{
    font-size: 13px;
}

.el-checkbox{
    margin-right: 5px;
}

.finalBtn{
    margin-top: 15px;
    float: right;
}
</style>
